<!DOCTYPE html>
<html lang=zh>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <meta name="renderer" content="webkit">
  <meta http-equiv="Cache-Control" content="no-transform" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no,email=no,adress=no">
  <!-- Color theme for statusbar -->
  <meta name="theme-color" content="#000000" />
  <!-- 强制页面在当前窗口以独立页面显示,防止别人在框架里调用页面 -->
  <meta http-equiv="window-target" content="_top" />
  <!-- 谷歌收录 -->
  <meta name="google-site-verification" content="-5hl8eC4wfapGZhZouwMVUcKG0iaynijVRJbqVlzXm4" />
  
  
  <title>MongoDB增删改查 | 鴻塵</title>
  <meta name="description" content="摘要：MongoDB学习过程中对CRUD用法的记录，毕竟好记性不如烂笔头。">
<meta property="og:type" content="article">
<meta property="og:title" content="MongoDB增删改查">
<meta property="og:url" content="https://hwame.top/20210716/mongodb-crud-operations.html">
<meta property="og:site_name" content="鴻塵">
<meta property="og:description" content="摘要：MongoDB学习过程中对CRUD用法的记录，毕竟好记性不如烂笔头。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-07-16T00:37:42.000Z">
<meta property="article:modified_time" content="2021-07-24T18:02:28.000Z">
<meta property="article:author" content="鴻塵">
<meta property="article:tag" content="MongoDB">
<meta name="twitter:card" content="summary">
  <!-- Canonical links -->
  <link rel="canonical" href="https://hwame.top/20210716/mongodb-crud-operations.html">
  
    <link rel="alternate" href="true" title="鴻塵" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png" type="image/x-icon">
  
  
<link rel="stylesheet" href="/css/style.css">

  
  
  
    <link href="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css" rel="stylesheet">
  
  
<meta name="generator" content="Hexo 5.4.2"></head>


<script src="https://cdn.jsdelivr.net/gh/bobcn/hexo_resize_image.js@master/hexo_resize_image.js"></script>
<body class="main-center theme-purple" itemscope itemtype="http://schema.org/WebPage">
  <header class="header" itemscope itemtype="http://schema.org/WPHeader">
  <div class="slimContent">
    <div class="navbar-header">
      
      
      <div class="profile-block text-center">
        <a id="avatar" href="https://hwame.top" target="_blank">
          <img class="img-circle img-rotate" src="https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg" width="200" height="200">
        </a>
        <h2 id="name" class="hidden-xs hidden-sm">鴻塵</h2>
        <h3 id="title" class="hidden-xs hidden-sm hidden-md">Pythoner, Data Analyst</h3>
        <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i> 湖北-武汉</small>
      </div>
      
      <div class="search" id="search-form-wrap">

    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="搜索" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i class="icon icon-search"></i></button>
            </span>
        </div>
    </form>
    <div class="ins-search">
  <div class="ins-search-mask"></div>
  <div class="ins-search-container">
    <div class="ins-input-wrapper">
      <input type="text" class="ins-search-input" placeholder="想要查找什么..." x-webkit-speech />
      <button type="button" class="close ins-close ins-selectable" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
    <div class="ins-section-wrapper">
      <div class="ins-section-container"></div>
    </div>
  </div>
</div>


</div>
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
      <ul class="nav navbar-nav main-nav menu-highlight">
        
        
        <li class="menu-item menu-item-home">
          <a href="/.">
            
            <i class="icon icon-home-fill"></i>
            
            <span class="menu-title">首页</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-archives">
          <a href="/archives">
            
            <i class="icon icon-archives-fill"></i>
            
            <span class="menu-title">归档</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-categories">
          <a href="/categories">
            
            <i class="icon icon-folder-open"></i>
            
            <span class="menu-title">分类</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-tags">
          <a href="/tags">
            
            <i class="icon icon-tags"></i>
            
            <span class="menu-title">标签</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-repository">
          <a href="/repository">
            
            <i class="icon icon-project"></i>
            
            <span class="menu-title">资源</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-gallery">
          <a href="/gallery">
            
            <i class="icon icon-delicious"></i>
            
            <span class="menu-title">相册</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-links">
          <a href="/links">
            
            <i class="icon icon-friendship"></i>
            
            <span class="menu-title">友链</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-about">
          <a href="/about">
            
            <i class="icon icon-cup-fill"></i>
            
            <span class="menu-title">关于</span>
          </a>
        </li>
        
      </ul>
      
	
    <ul class="social-links">
    	
        <li><a href="https://github.com/hwame" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="https://weibo.com/hwamei" target="_blank" title="Weibo" data-toggle=tooltip data-placement=top><i class="icon icon-weibo"></i></a></li>
        
        <li><a href="https://www.zhihu.com/people/hwame" target="_blank" title="Zhihu" data-toggle=tooltip data-placement=top><i class="icon icon-zhihu"></i></a></li>
        
        <li><a href="https://segmentfault.com/u/hwame" target="_blank" title="Segmentfault" data-toggle=tooltip data-placement=top><i class="icon icon-segmentfault"></i></a></li>
        
        <li><a href="https://gitee.com/hwame" target="_blank" title="Gitee" data-toggle=tooltip data-placement=top><i class="icon icon-gitee"></i></a></li>
        
        <li><a href="/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    </nav>
  </div>
</header>

  
    <aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-stackexchange"></i>公告</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">
                <p>欢迎来到鴻塵的博客!<br>鴻塵的<u><a target="_blank" rel="noopener" href="https://weibo.com/hwamei" style="color:#E541E5;">微博</a></u>主页，鴻塵的<u><a target="_blank" rel="noopener" href="https://github.com/hwame" style="color:#E541E5;">Github</a></u>主页，如果我可以忘记的<u><a target="_blank" rel="noopener" href="https://www.zhihu.com/people/hwame" style="color:#E541E5;">知乎</a></u>主页。</p>
            </div>
        </div>
    </div>
</div>

    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-tags"></i>标签云</h3>
    <div class="widget-body tagcloud">
      <a href="/tags/CentOS/" style="font-size: 13px; color: #fff">CentOS</a> <a href="/tags/Go/" style="font-size: 13.2px; color: #fff">Go</a> <a href="/tags/Hexo/" style="font-size: 13.8px; color: #fff">Hexo</a> <a href="/tags/Linux/" style="font-size: 14px; color: #fff">Linux</a> <a href="/tags/Linux%E9%83%A8%E7%BD%B2/" style="font-size: 13px; color: #fff">Linux部署</a> <a href="/tags/MongoDB/" style="font-size: 13.4px; color: #fff">MongoDB</a> <a href="/tags/Spark/" style="font-size: 13px; color: #fff">Spark</a> <a href="/tags/matplotlib/" style="font-size: 13.2px; color: #fff">matplotlib</a> <a href="/tags/miscellanea/" style="font-size: 13.6px; color: #fff">miscellanea</a> <a href="/tags/python/" style="font-size: 14px; color: #fff">python</a> <a href="/tags/shell/" style="font-size: 13.6px; color: #fff">shell</a> <a href="/tags/%E5%A4%A7%E6%95%B0%E6%8D%AE/" style="font-size: 13px; color: #fff">大数据</a> <a href="/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/" style="font-size: 13px; color: #fff">数据结构与算法</a> <a href="/tags/%E7%88%AC%E8%99%AB/" style="font-size: 13px; color: #fff">爬虫</a>
    </div>
  </div>

<script type="text/javascript">
    var everytag=document.getElementsByClassName("widget-body tagcloud")[0].children;
    for (var i = everytag.length - 1; i >= 0; i--) {
    	var r=Math.floor(Math.random()*255);
        var g=Math.floor(Math.random()*255);
        var b=Math.floor(Math.random()*255);
        everytag[i].style.background = "rgb("+r+","+g+","+b+")";
    }
</script>
    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-folder-open"></i>分类</h3>
    <div class="widget-body">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/Go/">Go</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Hexo/">Hexo</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Linux/">Linux</a><span class="category-list-count">8</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/MongoDB/">MongoDB</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/miscellanea/">miscellanea</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/python/">python</a><span class="category-list-count">7</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/">数据结构与算法</a><span class="category-list-count">1</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-archives-fill"></i>归档</h3>
    <div class="widget-body">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2022/">2022</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/">2021</a><span class="archive-list-count">9</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/">2020</a><span class="archive-list-count">17</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-shu-fill"></i>最新文章</h3>
    <div class="widget-body">
      <ul class="recent-post-list list-unstyled ">
        
          <li>
            
            <div class="item-thumb">
              <a href="/20220327/channel-and-goroutine-in-go.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/post-pics/icon-golang.jpeg)" alt="Go语言中的通道" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/Go/">Go</a>
              </p>
              <p class="item-title">
                <a href="/20220327/channel-and-goroutine-in-go.html" class="title">Go语言中的通道</a>
              </p>
              <p class="item-date">
                <time datetime="2022-03-27T11:06:16.000Z" itemprop="datePublished">2022-03-27</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20220323/when-to-use-pointer-in-go.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/post-pics/icon-golang.jpeg)" alt="Go语言什么时候使用指针" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/Go/">Go</a>
              </p>
              <p class="item-title">
                <a href="/20220323/when-to-use-pointer-in-go.html" class="title">Go语言什么时候使用指针</a>
              </p>
              <p class="item-date">
                <time datetime="2022-03-23T12:49:57.000Z" itemprop="datePublished">2022-03-23</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20220228/awesome-images-in-markdown.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg)" alt="Markdown中图片的高级用法" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/miscellanea/">miscellanea</a>
              </p>
              <p class="item-title">
                <a href="/20220228/awesome-images-in-markdown.html" class="title">Markdown中图片的高级用法</a>
              </p>
              <p class="item-date">
                <time datetime="2022-02-28T15:27:50.000Z" itemprop="datePublished">2022-02-28</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20220116/shell-regular-expression.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/post-pics/linux-icon.png)" alt="Shell正则表达式" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/Linux/">Linux</a>
              </p>
              <p class="item-title">
                <a href="/20220116/shell-regular-expression.html" class="title">Shell正则表达式</a>
              </p>
              <p class="item-date">
                <time datetime="2022-01-16T14:13:05.000Z" itemprop="datePublished">2022-01-16</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20211009/install-linux-on-android-phone.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg)" alt="如何在安卓手机上安装Linux发行版" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/miscellanea/">miscellanea</a>
              </p>
              <p class="item-title">
                <a href="/20211009/install-linux-on-android-phone.html" class="title">如何在安卓手机上安装Linux发行版</a>
              </p>
              <p class="item-date">
                <time datetime="2021-10-09T15:16:37.000Z" itemprop="datePublished">2021-10-09</time>
              </p>
            </div>
          </li>
          
      </ul>
    </div>
  </div>
  

    
  </div>
</aside>

  
  
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <nav id="toc" class="article-toc">
      <h3 class="toc-title">文章目录</h3>
      <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E6%A6%82%E8%BF%B0"><span class="toc-number">1.</span> <span class="toc-text">1.概述</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-%E5%86%99%E4%BD%9C%E7%9A%84%E5%8A%A8%E6%9C%BA"><span class="toc-number">1.1.</span> <span class="toc-text">1.1.写作的动机</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-%E5%95%83%E6%96%87%E6%A1%A3%E7%9A%84%E4%B8%80%E4%BA%9B%E6%84%9F%E5%8F%97"><span class="toc-number">1.2.</span> <span class="toc-text">1.2.啃文档的一些感受</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E5%88%9B%E5%BB%BA%E6%93%8D%E4%BD%9C"><span class="toc-number">2.</span> <span class="toc-text">2.创建操作</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-%E6%9F%A5%E8%AF%A2%E6%93%8D%E4%BD%9C"><span class="toc-number">3.</span> <span class="toc-text">3.查询操作</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-%E6%9F%A5%E8%AF%A2%E5%B5%8C%E5%85%A5-%E5%B5%8C%E5%A5%97%E6%96%87%E6%A1%A3"><span class="toc-number">3.1.</span> <span class="toc-text">3.1.查询嵌入&#x2F;嵌套文档</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-%E6%9F%A5%E8%AF%A2%E6%95%B0%E7%BB%84"><span class="toc-number">3.2.</span> <span class="toc-text">3.2.查询数组</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-3-%E6%9F%A5%E8%AF%A2%E5%B5%8C%E5%A5%97%E6%96%87%E6%A1%A3%E6%95%B0%E7%BB%84"><span class="toc-number">3.3.</span> <span class="toc-text">3.3.查询嵌套文档数组</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-4-%E4%BB%8E%E6%9F%A5%E8%AF%A2%E8%BF%94%E5%9B%9E%E6%8C%87%E5%AE%9A%E5%AD%97%E6%AE%B5"><span class="toc-number">3.4.</span> <span class="toc-text">3.4.从查询返回指定字段</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-5-%E6%9F%A5%E8%AF%A2%E7%A9%BA%E5%AD%97%E6%AE%B5%E6%88%96%E7%BC%BA%E5%A4%B1%E5%AD%97%E6%AE%B5"><span class="toc-number">3.5.</span> <span class="toc-text">3.5.查询空字段或缺失字段</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-%E6%9B%B4%E6%96%B0%E6%93%8D%E4%BD%9C"><span class="toc-number">4.</span> <span class="toc-text">4.更新操作</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BE%8B1%EF%BC%9A%E6%9B%B4%E6%96%B0%E5%8D%95%E4%B8%AA%E6%96%87%E6%A1%A3"><span class="toc-number">4.1.</span> <span class="toc-text">例1：更新单个文档</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BE%8B2%EF%BC%9A%E6%9B%B4%E6%96%B0%E5%A4%9A%E4%B8%AA%E6%96%87%E6%A1%A3"><span class="toc-number">4.2.</span> <span class="toc-text">例2：更新多个文档</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BE%8B3-%E6%9B%BF%E6%8D%A2%E5%8D%95%E4%B8%AA%E6%96%87%E6%A1%A3"><span class="toc-number">4.3.</span> <span class="toc-text">例3:替换单个文档</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E8%81%9A%E5%90%88%E7%AE%A1%E9%81%93%E6%9B%B4%E6%96%B0"><span class="toc-number">4.4.</span> <span class="toc-text">使用聚合管道更新</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#update%E6%96%B9%E6%B3%95"><span class="toc-number">4.5.</span> <span class="toc-text">update方法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-%E5%88%A0%E9%99%A4%E6%93%8D%E4%BD%9C"><span class="toc-number">5.</span> <span class="toc-text">5.删除操作</span></a></li></ol>
    </nav>
  </div>
</aside>

<main class="main" role="main">
  <div class="content">
  <article id="post-mongodb-crud-operations" class="article article-type-post" itemscope itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      
        
  
    <h1 class="article-title" itemprop="name">
      MongoDB增删改查
    </h1>
  

      
      <div class="article-meta">
        <span class="article-date">
    <i class="icon icon-calendar"></i>
	<a href="/20210716/mongodb-crud-operations.html" class="article-date">
	  发布于 <time datetime="2021-07-16T00:37:42.000Z" itemprop="datePublished">2021-07-16</time>
	</a>
</span>
<span class="article-date">
    <i class="icon icon-calendar-check"></i>
	<a href="/20210716/mongodb-crud-operations.html" class="article-date">
	  更新于 <time datetime="2021-07-24T18:02:28.000Z" itemprop="dateUpdated">2021-07-25</time>
	</a>
</span>
        
  <span class="article-category">
    <i class="icon icon-folder"></i>
    <a class="article-category-link" href="/categories/MongoDB/">MongoDB</a>
  </span>

        
  <span class="article-tag">
    <i class="icon icon-tags"></i>
	<a class="article-tag-link-link" href="/tags/MongoDB/" rel="tag">MongoDB</a>
  </span>


        

	<span class="article-read hidden-xs">
    	<i class="icon icon-eye-fill" aria-hidden="true"></i>
    	<span id="/20210716/mongodb-crud-operations.html" class="leancloud_visitors"  data-flag-title="MongoDB增删改查">
			<span class="leancloud-visitors-count">0</span>
		</span>
    </span>

        <span class="post-comment"><i class="icon icon-comment"></i> <a href="/20210716/mongodb-crud-operations.html#comments" class="article-comment-link">评论</a></span>
        
	
		<span class="post-wordcount hidden-xs" itemprop="wordCount">字数统计: 5.9k(字)</span>
	
	
		<span class="post-readcount hidden-xs" itemprop="timeRequired">阅读时长: 27(分)</span>
	

      </div>
      <div style="background-color:#D7BDE2;border:1px solid #D7BDE2;border-radius:10px;padding:5px">
          <b>温馨提示</b>：点击页面下方<i style="color:red" class="icon icon-anchor"></i>以展开或折叠目录
      </div>
    </div>
    <div class="article-entry marked-body" itemprop="articleBody">
      
        <p>摘要：MongoDB学习过程中对CRUD用法的记录，毕竟好记性不如烂笔头。<span id="more"></span></p>
<blockquote>
<p><font size=5><b>文章说明</b></font><br><strong>文章作者：</strong>鴻塵<br><strong>文章链接：</strong><a href="https://hwame.top/20210716/mongodb-crud-operations.html">https://hwame.top/20210716/mongodb-crud-operations.html</a><br><strong>参考资料：</strong><a target="_blank" rel="noopener" href="https://docs.mongodb.com/manual/crud/">MongoDB CRUD Operations: Version 5.0 latest</a></p>
</blockquote>
<h2 id="1-概述"><a href="#1-概述" class="headerlink" title="1.概述"></a>1.概述</h2><h3 id="1-1-写作的动机"><a href="#1-1-写作的动机" class="headerlink" title="1.1.写作的动机"></a>1.1.写作的动机</h3><p>由于工作需要，捡起了遗忘多时的MongoDB，项目中使用的是4.2版本，恰好本地电脑上多年前装的也是4.2版本，如今官方文档都已经更新到5.0了。</p>
<p>相比旧版本，5.0增加了一些新功能，比如聚合里的一些stage，4.2版本算是一个比较经典的版本吧（就好比mysql的5.7和8.0）。</p>
<p>决定记录的另一个动机，则是网上的教程不够全面，官方文档也没有中文版的，有些翻译很生硬且不准确：</p>
<ul>
<li><a target="_blank" rel="noopener" href="https://www.bookstack.cn/">书栈网</a><ul>
<li>英文版教程<a target="_blank" rel="noopener" href="https://www.bookstack.cn/books/mongodb-4.2-manual">MongoDB v4.2 Manual</a>，与官方文档无异。</li>
<li><a target="_blank" rel="noopener" href="https://www.bookstack.cn/books/mongodb-doc-cn">MongoDB (v3.4) 中文手册</a>翻译不全，很多章节仍然是英文。</li>
<li><a target="_blank" rel="noopener" href="https://www.bookstack.cn/books/Getting-Started-with-MongoDB">MongoDB入门指南</a>和<a target="_blank" rel="noopener" href="https://www.bookstack.cn/books/linfenliang-mongodb">MongoDB学习总结</a>过于简洁、不够全面。</li>
<li><a target="_blank" rel="noopener" href="https://www.bookstack.cn/books/aliyun-mongodb">MongoDB数据库最佳实践</a>更侧重于实际应用，适合于进阶实战。</li>
</ul>
</li>
<li><a target="_blank" rel="noopener" href="https://www.runoob.com">菜鸟教程</a>的<a target="_blank" rel="noopener" href="https://www.runoob.com/mongodb/mongodb-tutorial.html">MongoDB教程</a>相比上面几个要好得多，但是毕竟偏向入门，很多细节没有展开。</li>
</ul>
<p>在比较之后遂决定啃<a target="_blank" rel="noopener" href="https://docs.mongodb.com/manual/crud/">最新的5.0官方文档</a>，怎么说呢，任何问题都可以从中找到答案。</p>
<blockquote>
<p>MongoDB提供了一个在线版的<a target="_blank" rel="noopener" href="https://mws.mongodb.com/">Mongo shell</a>，默认为<code>latest</code>即v5.0，可以通过参数选择版本，例如<a target="_blank" rel="noopener" href="https://mws.mongodb.com/?version=4.2">https://mws.mongodb.com/?version=4.2</a>。<br>唯一的缺点就是连接维持的时间比较短，一不留神就断开了，重连会丢失之前的数据。</p>
</blockquote>
<h3 id="1-2-啃文档的一些感受"><a href="#1-2-啃文档的一些感受" class="headerlink" title="1.2.啃文档的一些感受"></a>1.2.啃文档的一些感受</h3><p>这篇文章写的是CRUD，是相对比较基础的部分，目前在看管道聚合，准备写下一篇。</p>
<p>在看过几天文档（尤其是管道聚合部分）后有一些感受，主要来自管道聚合，但是估计下一篇内容会很多，这篇内容较少就放在这里吧。主要有以下几点：</p>
<ul>
<li><font color=purple><b>①官方文档写的很细</b></font>，例如<a target="_blank" rel="noopener" href="https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/">Aggregation Pipeline Stages</a>和<a target="_blank" rel="noopener" href="https://docs.mongodb.com/manual/reference/operator/aggregation/">Aggregation Pipeline Operators</a>都有名为<code>$count</code>的<strong>累积器accumulator</strong>和<strong>管道阶段stage</strong>，<a target="_blank" rel="noopener" href="https://docs.mongodb.com/manual/reference/operator/aggregation/">Aggregation Pipeline Operators</a>里有分别名为<code>$first</code>和<code>$last</code>的同名<strong>累积器accumulator</strong>和<strong>操作符operator</strong>。文档不厌其烦地在每个出现的地方都有「消除歧义<strong>Disambiguation</strong>」的提示，但这也导致了文档比较冗杂。</li>
<li><font color=purple><b>②官方文档内容比较混乱</b></font>，从路由上就可以看出来。比如<a target="_blank" rel="noopener" href="https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/">Aggregation Pipeline Stages</a>和<a target="_blank" rel="noopener" href="https://docs.mongodb.com/manual/reference/operator/aggregation/">Aggregation Pipeline Operators</a>路由的命名分别为<code>aggregation-pipeline</code>和<code>aggregation</code>，但是这两个对应的类似<code>$xxx</code>的格式却都是<code>https://docs.mongodb.com/manual/reference/operator/aggregation/xxx/</code>，这难免让人摸不着头脑。为何不将路由命名为<code>aggregation-pipeline-stages</code>和<code>aggregation-pipeline-operators</code>，且将对应<code>$xxx</code>放到各自路径下呢？</li>
<li><font color=purple><b>③官方文档内容分类不够具体</b></font>，如果能按分类添加下级路由，那么文档的结构和层次会更清楚了。如下两例：<ul>
<li>例如，<a target="_blank" rel="noopener" href="https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/">Aggregation Pipeline Stages</a>可分为「<strong><em><code>db.collection.aggregate()</code>Stages</em></strong>」、「<strong><em><code>db.aggregate()</code>Stages</em></strong>」和「<strong><em>Stages Available for Updates</em></strong>」三个部分，完全可以添加三个子路由啊。</li>
<li>还有，<a target="_blank" rel="noopener" href="https://docs.mongodb.com/manual/reference/operator/aggregation/">Aggregation Pipeline Operators</a>操作表达式分为「<strong><em>算术表达式操作符</em></strong>」、「<strong><em>数组表达式操作符</em></strong>」、「<strong><em>布尔表达式操作符</em></strong>」、「<strong><em>比较表达式操作符</em></strong>」、「<strong><em>条件表达式操作符</em></strong>」、「<strong><em>自定义聚合表达式操作符</em></strong>」、「<strong><em>数据尺寸操作符</em></strong>」、「<strong><em>日期表达式操作符</em></strong>」、「<strong><em>字面表达式操作符</em></strong>」、「<strong><em>杂项操作符</em></strong>」、「<strong><em>对象表达式操作符</em></strong>」、「<strong><em><code>set</code>表达式操作符</em></strong>」、「<strong><em>字符串表达式操作符</em></strong>」、「<strong><em>文本表达式操作符</em></strong>」、「<strong><em>三角函数表达式操作符</em></strong>」、「<strong><em>类型表达式操作符</em></strong>」、「<strong><em><code>$group</code>阶段的累积器</em></strong>」、「<strong><em>非<code>$group</code>阶段的累积器</em></strong>」、「<strong><em>变量表达式操作符</em></strong>」和「<strong><em>窗口操作符</em></strong>」。单单是分类就已经有20个之多，内容那就更多了。如果按分类添加20个子路由，文档的结构和层次会更清楚了。</li>
<li>当然，文档很贴心地在<a target="_blank" rel="noopener" href="https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/">Aggregation Pipeline Stages</a>和<a target="_blank" rel="noopener" href="https://docs.mongodb.com/manual/reference/operator/aggregation/">Aggregation Pipeline Operators</a>最后添加了按字母排序的列表（Alphabetical Listing）以供索引查阅。需要说明的是，各分类并不是互斥的，各类里面有重叠的项，大概这就是官方不予添加子路由的原因吧。</li>
</ul>
</li>
<li><font color=purple><b>④相近的概念没有辨析清楚</b></font>【这里应该与翻译和表达有关，不全是官方的锅】，比如「管道聚合」里的stage和operation是并列的，operator用于stage/operation里，中文里「<strong>操作</strong>」一词即可作名词也可做动词，翻译阅读起来就会产生歧义，所以我把stage和operation统一当成「<strong>阶段</strong>」，operator则称为「<strong>操作符</strong>」或「<strong>操作表达式</strong>」。从这个层面上说，官方文档的描述还是很准确的，只不过全是长难句一连串的定语有时候都分不清修饰的到底是谁，引起理解上的歧义。</li>
</ul>
<p>我们常说的CRUD即是「增删改查」，具体说来：</p>
<ul>
<li><code>C</code>＝<code>Create</code>，增，即创建操作；</li>
<li><code>R</code>＝ <code>Read</code> ，查，即查询操作；</li>
<li><code>U</code>＝<code>Update</code>，改，即更新操作；</li>
<li><code>D</code>＝<code>Delete</code>，删，即删除操作。</li>
</ul>
<h2 id="2-创建操作"><a href="#2-创建操作" class="headerlink" title="2.创建操作"></a>2.创建操作</h2><p>创建/插入是针对单个集合而言，「写操作」在单个文档级别上具有「原子性」。如果当前集合不存在，则插入操作将创建该集合。<br><figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 插入单个文档是「&#123;&#125;」，多个是「[&#123;&#125;, &#123;&#125;, ...]」</span></span><br><span class="line"><span class="string">db.collection.insertOne()</span>  <span class="comment"># 单个</span></span><br><span class="line"><span class="string">db.collection.insertMany()</span> <span class="comment"># 多个</span></span><br><span class="line"><span class="string">db.collection.insert()</span>     <span class="comment"># 单个或多个</span></span><br></pre></td></tr></table></figure><br>与<code>upsert: true</code> <strong>选项</strong> 一起使用时也可实现插入:</p>
<ul>
<li><code>db.collection.update()</code>，<code>db.collection.updateOne()</code>，<code>db.collection.updateMany()</code>；</li>
<li><code>db.collection.findAndModify()</code>，<code>db.collection.findOneAndUpdate()</code>，<code>db.collection.findOneAndReplace()</code>；</li>
<li><code>db.collection.bulkWrite()</code>：<strong><em>Performs multiple write operations with controls for order of execution</em></strong>。</li>
</ul>
<h2 id="3-查询操作"><a href="#3-查询操作" class="headerlink" title="3.查询操作"></a>3.查询操作</h2><p>查询操作语法为<code>db.collection.find(query, projection)</code>，其中<code>query</code>指定查询条件，<code>projection</code>指定返回的字段。</p>
<p>以下示例使用<code>inventory</code>集合，包含如下数据：<br><figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#123; <span class="attr">item:</span> <span class="string">&quot;journal&quot;</span>, <span class="attr">qty:</span> <span class="number">25</span>, <span class="attr">size:</span> &#123; <span class="attr">h:</span> <span class="number">14</span>, <span class="attr">w:</span> <span class="number">21</span>, <span class="attr">uom:</span> <span class="string">&quot;cm&quot;</span> &#125;, <span class="attr">status:</span> <span class="string">&quot;A&quot;</span> &#125;</span><br><span class="line">&#123; <span class="attr">item:</span> <span class="string">&quot;notebook&quot;</span>, <span class="attr">qty:</span> <span class="number">50</span>, <span class="attr">size:</span> &#123; <span class="attr">h:</span> <span class="number">8.5</span>, <span class="attr">w:</span> <span class="number">11</span>, <span class="attr">uom:</span> <span class="string">&quot;in&quot;</span> &#125;, <span class="attr">status:</span> <span class="string">&quot;A&quot;</span> &#125;</span><br><span class="line">&#123; <span class="attr">item:</span> <span class="string">&quot;paper&quot;</span>, <span class="attr">qty:</span> <span class="number">100</span>, <span class="attr">size:</span> &#123; <span class="attr">h:</span> <span class="number">8.5</span>, <span class="attr">w:</span> <span class="number">11</span>, <span class="attr">uom:</span> <span class="string">&quot;in&quot;</span> &#125;, <span class="attr">status:</span> <span class="string">&quot;D&quot;</span> &#125;</span><br><span class="line">&#123; <span class="attr">item:</span> <span class="string">&quot;planner&quot;</span>, <span class="attr">qty:</span> <span class="number">75</span>, <span class="attr">size:</span> &#123; <span class="attr">h:</span> <span class="number">22.85</span>, <span class="attr">w:</span> <span class="number">30</span>, <span class="attr">uom:</span> <span class="string">&quot;cm&quot;</span> &#125;, <span class="attr">status:</span> <span class="string">&quot;D&quot;</span> &#125;</span><br><span class="line">&#123; <span class="attr">item:</span> <span class="string">&quot;postcard&quot;</span>, <span class="attr">qty:</span> <span class="number">45</span>, <span class="attr">size:</span> &#123; <span class="attr">h:</span> <span class="number">10</span>, <span class="attr">w:</span> <span class="number">15.25</span>, <span class="attr">uom:</span> <span class="string">&quot;cm&quot;</span> &#125;, <span class="attr">status:</span> <span class="string">&quot;A&quot;</span> &#125;</span><br></pre></td></tr></table></figure></p>
<ol>
<li>选择集合中的所有文档：<code>query=&#123;&#125;</code>或<code>query=</code>（留空不写），相当于<code>SELECT * FROM inventory</code>。</li>
<li>指定相等条件：<code>query=&#123;&lt;field1&gt;: &lt;valve1&gt;, ...&#125;</code>，例如<code>&#123;status: &quot;D&quot;&#125;</code>相当于<code>SELECT * FROM inventory WHERE status = &quot;D&quot;</code>。</li>
<li>使用查询运算符（Query Operators）指定条件：<code>&#123;&lt;field1&gt;: &#123;&lt;operator1&gt;: &lt;value1&gt;&#125;, ...&#125;</code>，例如<code>&#123;status: &#123;$in: [&quot;A&quot;, &quot;D&quot;]&#125;&#125;</code>相当于<code>SELECT * FROM inventory WHERE status in (&quot;A&quot;, &quot;D&quot;)</code>【此处也可用<code>$or</code>，但对同一字段应该用<code>$in</code>而非<code>$or</code>】。</li>
<li>指定<code>AND</code>条件：<code>&#123;&lt;and1&gt;: &lt;value1&gt;, &lt;and2&gt;: &lt;value2&gt;, ...&#125;</code>，例如<code>&#123;status: &quot;A&quot;, qty: &#123;$lt: 30&#125;&#125;</code>相当于<code>SELECT * FRON inventory WHERE status = &quot;A&quot; AND qty &lt; 30</code>。</li>
<li>指定<code>OR</code>条件：<code>&#123;$or: [&lt;query1&gt;, &lt;query2&gt;, ...]&#125;</code>，例如<code>&#123;$or: [&#123;status: “A&quot;&#125;, &#123;qty: &#123;$lt: 30&#125;&#125;]&#125;</code>相当于<code>SELECT * FROM inventory WHERE status = &quot;A&quot; OR qty &lt; 30</code>。</li>
<li>指定<code>AND</code>以及<code>OR</code>条件【即 <strong><code>4＋5</code></strong> 组含】：<code>&lt;and&gt;: &lt;value&gt;, $or: [&lt;query1&gt;, &lt;query2&gt;, ...]</code>，例如<code>&#123;status: &quot;A&quot;, $or: [qty: &#123;$lt: 30&#125;&#125;, &#123;item: /^p/&#125;]&#125;</code>相当于<code>SELECT * FROM inventory WHERE status = &quot;A&quot; AND (qty &lt; 30 OR item LIKE &quot;p%&quot;)</code>【支持正则表达式】。</li>
</ol>
<h3 id="3-1-查询嵌入-嵌套文档"><a href="#3-1-查询嵌入-嵌套文档" class="headerlink" title="3.1.查询嵌入/嵌套文档"></a>3.1.查询嵌入/嵌套文档</h3><ul>
<li>嵌套文档匹配即<code>&lt;value = document&gt;</code>，格式为：<code>query=&#123;&lt;field1&gt;: &lt;doc1&gt;, ...&#125;</code>，例如<code>&#123;size: &#123;h: 14, w: 21，uom: &quot;cm&quot;&#125;&#125;</code>；<strong>注意: </strong>整个嵌入文档的相等匹配需要精确匹配，包括顺序!</li>
<li>嵌套字段匹配即嵌套文挡中字殿的匹配，字段使用点表示法：<code>field.subField</code>。<ul>
<li>相等匹配：<code>&#123;&lt;field.subField&gt;: &lt;value&gt;, ...&#125;</code>，例如<code>&#123;&quot;size.uom&quot;: &quot;in&quot;&#125;</code>；</li>
<li>查询运算符：<code>&#123;&lt;field1&gt;: &#123;&lt;operator1&gt;: &lt;value1&gt;&#125;, ...&#125;</code>，例如<code>&#123;&quot;size.h&quot;: &#123;$lt: 15&#125;&#125;</code>，与 <strong>3.</strong> 相同；</li>
<li>指定<code>AND</code>条件：<code>&#123;&lt;field1.subField1&gt;: &lt;valuel&gt;, ...&#125;</code>，例加<code>&#123;&quot;size.h&quot;: &#123;$lt: 15&#125;, &quot;size.uom&quot;: &quot;in&quot;, states: &quot;D&quot;&#125;</code>，与 <strong>4.</strong> 相同。</li>
</ul>
</li>
</ul>
<h3 id="3-2-查询数组"><a href="#3-2-查询数组" class="headerlink" title="3.2.查询数组"></a>3.2.查询数组</h3><ul>
<li>匹配一个数组，即<code>value = array</code>，精确匹配包括顺序。<ul>
<li>例如<code>&#123;tags: [&quot;red&quot;, &quot;black&quot;]&#125;</code>只匹配包含2个元素的定序的<code>[&quot;red&quot;, &quot;black&quot;]</code>；</li>
<li>若要匹配无序的包含此2元素的数组（<code>len ≥ 2</code>），则需使用<code>$all</code>运算符：<code>&#123;tags: &#123;$all: [&quot;red&quot;, &quot;black&quot;]&#125;&#125;</code>。</li>
</ul>
</li>
<li>查询一个元素的数组（包含指定元素的数组），即<code>arrField = arrValue</code>。<ul>
<li>例如<code>&#123;tags: &quot;red&quot;&#125;</code>匹配<code>&quot;red&quot; in array(tags)</code>；</li>
<li>可以对<code>arrValue</code>指定条件过滤器，即<code>&#123;arrField1: &#123;operator1: value1, ...&#125;&#125;</code>，例如<code>&#123;dim_cm: &#123;$gt: 25&#125;&#125;</code>匹配<code>any(dim_cm[i] &gt; 25)</code>，即<code>dim_cm</code>中存在大于25的元素。</li>
</ul>
</li>
<li>为数组元素指定多个条件（复合条件），使 <strong>单个数组元素</strong> 满足这些条件或 <strong>数组元素的任意组合</strong> 满足条件。<ul>
<li><em>在数组元素上使用复合过滤条件查询数组</em>：数组中存在满足条件的元素（这些元素同时存在于该数组即可，无需是同一个元素），例如<code>&#123;dim_cm: &#123;Sgt: 15, slt: 20&#125;&#125;</code>表示<code>dim_cm[i] &gt; 15 AND dim_cm[j] &lt; 20</code>或<code>15 &lt; dim_cm[kJ &lt; 20</code>；</li>
<li><em>查询满足多个条件的数组元素</em>：一个元素同时满足条件，例如<code>&#123;dim_cm: &#123;$elemMatch: &#123;Sgt: 15, $lt: 20&#125;&#125;&#125;</code>表示<code>15 &lt; dim_cm[i] &lt; 20</code>；</li>
<li><em>通过数组索引位置查询元素</em>：点表示法（dot notation）可以为指定位置的元素设置条件，索引从0开始【 <strong>字段和嵌套字段必须在引号内</strong> 】，例如<code>&#123;&quot;dim_cm.1&quot;: &#123;$gt: 25&#125;&#125;</code>表示<code>dim_cm[1] &gt; 25</code>；</li>
<li><em>按数组长度查询数组</em>：<code>&#123;&quot;tags&quot;: &#123;$size: 3&#125;&#125;</code>表示<code>len(tags) = 3</code>。</li>
</ul>
</li>
</ul>
<h3 id="3-3-查询嵌套文档数组"><a href="#3-3-查询嵌套文档数组" class="headerlink" title="3.3.查询嵌套文档数组"></a>3.3.查询嵌套文档数组</h3><blockquote>
<p>嵌套文档数组（Array of Embedded Documents）即以文档为元素的数组，集合<code>inventory</code>文档格式为<code>&#123;item: &quot;xx&quot;, instock: [&#123;warehouse: &quot;A&quot;, qty: 5&#125;, &#123;&#125;...]&#125;</code>。</p>
</blockquote>
<ul>
<li>查询嵌套在数组中的文档：<code>&#123;field: doc&#125;</code>即<code>doc in array(field)</code>（查询数组2：包含指定元素的数组），<code>doc</code>精确匹配包括顺序。例如<code>&#123;&quot;instock&quot;: &#123;warehouse: &quot;A&quot;, qty: 5&#125;&#125;</code>匹配的数组<code>instock</code>包含整个「有序」文档<code>&#123;warehouse: &quot;A&quot;, qty: 5&#125;</code>。</li>
<li>在文档数组中的字段上指定查询条件【点表示法 <strong>字段和嵌套字段必须在引号内</strong> 】。<ul>
<li>对嵌入在文档数组中的字段指定查询条件：例如<code>&#123;&#39;instock.qty&#39;: &#123;$lte: 20&#125;&#125;</code>匹配数组元素<code>instock[i] = doc，doc.qty ≤ 20</code>，不检查<code>doc</code>位置；</li>
<li>使用数组索引查询嵌入文档中的字段: 例如<code>&#123;&#39;instock.0.qty&#39;: &#123;$lte: 20&#125;&#125;</code>匹配数组元素<code>instock[0] = doc，doc.qty ≤ 20</code>，指定<code>doc</code>位置为0，因此结果是上一个的 <strong>子集</strong> 。</li>
</ul>
</li>
<li>为文档数组指定多个条件，使得数组中的文档或文档组合满足条件。<ul>
<li>单个嵌套文档在嵌套字段上满足多个查询条件，例如<code>&#123;&quot;instock&quot;: &#123;$elemMatch: &#123;qty: 5, warehouse: &quot;A&quot;&#125;&#125;&#125;</code>匹配<code>instock[i]=doc，&#123;qty: 5, warehouse: &quot;A&quot;&#125; in doc</code>，此处<code>doc</code>包含这两值即可且无序。再如<code>&#123;&quot;instock&quot;: &#123;$elemMatch: &#123;qty: &#123;$gt: 10, $lte: 20&#125;&#125;&#125;&#125;</code>匹配<code>instock[i]=doc，10 &lt; doc.qty &lt; 20</code>；</li>
<li>元素组合满足条件， 若数组字段上的复合查询条件不使用<code>$elemMatch</code>运算行，则匹配「文档组合满足条件的数组」，注意是 <strong>文档组合</strong> 满足而非 <strong>文档</strong> 满足。例如<code>&#123;&quot;instock.qty&quot;: &#123;$gt: 10, $lte: 20&#125;&#125;</code>匹配<code>instock[i].qty &gt; 10，instock[j].qty &lt; 20</code>【上一个是单个文档同时满足，使用了<code>$elemMatch</code>】。类似的，<code>&#123;&quot;instock.qty&quot;: 5, &quot;instock.warehouse&quot;: &quot;A&quot;&#125;</code>将匹配<code>instock[i].qty = 5，instock[j].warehouse = &quot;A&quot;</code>而不要求位于同一文档中。</li>
</ul>
</li>
</ul>
<h3 id="3-4-从查询返回指定字段"><a href="#3-4-从查询返回指定字段" class="headerlink" title="3.4.从查询返回指定字段"></a>3.4.从查询返回指定字段</h3><blockquote>
<p>从查询返回指定字段即投影（Projection），查询语法<code>db.inventory.find(query, projection)</code>，其中<code>projection.field = (1=true | 0=false)</code>。<br>查询默认返回所有字段【相当于<code>SELECT *</code>】，使用投影（Projection）来指定或限制返回的字段【相当于<code>SELECT field1, field2...</code>】。</p>
</blockquote>
<ul>
<li>返回匹配文档中的所有字段：不指定<code>projection</code>相当于<code>SELECT *</code>。</li>
<li>仅返回指定字段和<code>_id</code>：<code>projection = &#123;field1: 1, field2: 1&#125;</code>，默认会返回<code>_id</code>字段，相当于<code>SELECT _id, field1, field2</code>。</li>
<li>禁用<code>_id</code>字段，通过 <strong>显式地置0</strong> 从结果中删除<code>_id</code>字段：<code>projection = &#123;field1: 1, field2: 1, _id: 0&#125;</code>。</li>
<li>返回除排除字段之外的所有字段（补集思想），通过置0来排除字段，返回剩下的字段。 <strong>注意：</strong> 除了<code>_id</code>字段以外，不能在<code>projection</code>文档中对「包含和排除语句」进行组合，即不能同时出现0和1。</li>
<li>返回/禁用嵌套文档中的特定字段：使用点表示法指定嵌套文档中的特定字段，如<code>projection = &#123;item: 1, status: 1, &quot;size.uom&quot;: 1&#125;</code>、<code>projection = &#123;&quot;size.uom&quot;: 0&#125;</code>。</li>
<li>数组中嵌入文档的投影，使用点表示法在嵌入数组的文档中投影特定字段，例如<code>projection = &#123;item: 1, status: 1, &quot;instock.qty&quot;: 1&#125;</code>的查询结果中<code>instock</code>数组元素（即<code>doc</code>文档）只有<code>qty</code>字段。</li>
<li>在返回的数组中投影指定数组元素：对于包含了数组的字段，投影算子<script type="math/tex">elemMatch`、`$slice`和`</script>用来操作数组。例如<code>projection = &#123;item: 1, status: 1, instock: &#123;$slice: -1&#125;&#125;</code> 表示只取<code>instock</code>数组最后一个元素。<blockquote>
<p>上述3个投影算子是「从返回数组中」投影「指定元素」的 <strong>唯一</strong> 方法。也就是说，不能使用素引<code>&#123;&quot;instock.0&quot;: 1&#125;</code>，将报错SyntaxError <code>expected property name, got &#39;&#123;&#39;</code>。</p>
</blockquote>
</li>
</ul>
<h3 id="3-5-查询空字段或缺失字段"><a href="#3-5-查询空字段或缺失字段" class="headerlink" title="3.5.查询空字段或缺失字段"></a>3.5.查询空字段或缺失字段</h3><p>MongoDB中的不同查询运算符对<code>null</code>值的处理方式不同。查询语法<code>db.inventory.find(query, projection)</code>，示例集合<code>inventory</code>为：<br><figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&#123; <span class="attr">_id:</span> <span class="number">1</span>, <span class="attr">item:</span> <span class="literal">null</span>&#125;</span><br><span class="line">&#123; <span class="attr">_id:</span> <span class="number">2</span>&#125;</span><br></pre></td></tr></table></figure></p>
<ul>
<li>相等过滤器：<code>query = &#123;item: null&#125;</code>查询匹配<code>item = null OR !item</code>，结果返回所有的两个文档。</li>
<li>类型检查：<code>query = &#123;item: &#123;$type: 10&#125;&#125;</code>查询匹配<code>item = null</code>即字段<code>item</code>的值为「BSON类型值<code>Null</code>，其类型编号为10」，结果返回<code>_id = 1</code>的文档。</li>
<li>存在检查，<code>$exists</code>检查是否存在指定字段：<code>query = &#123;item: &#123;$exists: false&#125;&#125;</code>查询匹配<code>!item</code>即<code>exists(item) = false</code>，结果返回<code>_id = 2</code>的文档（不包含<code>item</code>字段）。</li>
</ul>
<h2 id="4-更新操作"><a href="#4-更新操作" class="headerlink" title="4.更新操作"></a>4.更新操作</h2><p>更新操作用于修改集合中已有的文档，在单个文档级别上具有「原子性」，<strong>（与「增」相同）</strong>。<br>可以指定条件或过滤器，来进行更新：<br><figure class="highlight reasonml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">db.collection.update<span class="constructor">One(&lt;<span class="params">filter</span>&gt;, &lt;<span class="params">update</span>&gt;, &lt;<span class="params">options</span>&gt;)</span></span><br><span class="line">db.collection.update<span class="constructor">Many(&lt;<span class="params">filter</span>&gt;, &lt;<span class="params">update</span>&gt;, &lt;<span class="params">options</span>&gt;)</span></span><br><span class="line">db.collection.replace<span class="constructor">One(&lt;<span class="params">filter</span>&gt;, &lt;<span class="params">update</span>&gt;, &lt;<span class="params">options</span>&gt;)</span></span><br></pre></td></tr></table></figure><br>利用<strong>更新操作符</strong>如<code>$set</code>来修改字段值，「更新方法」的格式：<br><strong>注意：</strong>如果字段不存在，某些更新运算符（例如<code>$set</code>）将创建该字段。<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="tag">&lt;<span class="name">update_operator1</span>&gt;</span>: &#123;<span class="tag">&lt;<span class="name">field1</span>&gt;</span>: <span class="tag">&lt;<span class="name">value1</span>&gt;</span>, ...&#125;,</span><br><span class="line">    <span class="tag">&lt;<span class="name">update_operator2</span>&gt;</span>: &#123;<span class="tag">&lt;<span class="name">field2</span>&gt;</span>: <span class="tag">&lt;<span class="name">value2</span>&gt;</span>, ...&#125;,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="例1：更新单个文档"><a href="#例1：更新单个文档" class="headerlink" title="例1：更新单个文档"></a>例1：更新单个文档</h3><p>例如原文档：<code>&#123;item: &quot;paper&quot;, qty: 100, size: &#123;h: 8.5, w: 11, uom: &quot;in&quot;&#125;, status: &quot;D&quot;&#125;</code>；<br>更新后文档：<code>&#123;item: &quot;paper&quot;, qty: 100, size: &#123;h: 8.5, w: 11, uom: &quot;cm&quot;&#125;, status: &quot;P&quot;, lastModified: ISODate(&quot;2021-07-21T02:40:43.515Z&quot;)&#125;</code>。<br>更新操作：</p>
<ul>
<li>使用<code>$set</code>修改<code>&quot;size.uom&quot; = &quot;cm&quot;</code>和<code>status = &quot;p&quot;</code>；</li>
<li>使用<code>$currentDate</code>将<code>lastModified</code>更新为当前日期，不存在的字段将被创建。</li>
</ul>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">db.inventory.updateOne(</span></span><br><span class="line">    &#123;<span class="attr">item:</span> <span class="string">&quot;paper&quot;</span>&#125;<span class="string">,</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="string">$set:</span> &#123;<span class="attr">&quot;size.uom&quot;:</span> <span class="string">&quot;cm&quot;</span>, <span class="attr">status:</span> <span class="string">&quot;P&quot;</span>&#125;,</span><br><span class="line">        <span class="string">$currentDate:</span> &#123;<span class="attr">lastModified:</span> <span class="literal">true</span>&#125;</span><br><span class="line">    &#125;</span><br><span class="line"><span class="string">)</span></span><br></pre></td></tr></table></figure>
<h3 id="例2：更新多个文档"><a href="#例2：更新多个文档" class="headerlink" title="例2：更新多个文档"></a>例2：更新多个文档</h3><figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 例如原文档</span></span><br><span class="line">&#123;<span class="attr">item:</span> <span class="string">&quot;journal&quot;</span>,  <span class="attr">qty:</span> <span class="number">25</span>, <span class="attr">size:</span> &#123;<span class="attr">h:</span> <span class="number">14</span>, <span class="attr">w:</span> <span class="number">21</span>,    <span class="attr">uom:</span> <span class="string">&quot;cm&quot;</span>&#125;, <span class="attr">status:</span> <span class="string">&quot;A&quot;</span>&#125;<span class="string">,</span></span><br><span class="line">&#123;<span class="attr">item:</span> <span class="string">&quot;mousepad&quot;</span>, <span class="attr">qty:</span> <span class="number">25</span>, <span class="attr">size:</span> &#123;<span class="attr">h:</span> <span class="number">19</span>, <span class="attr">w:</span> <span class="number">22.85</span>, <span class="attr">uom:</span> <span class="string">&quot;cm&quot;</span>&#125;, <span class="attr">status:</span> <span class="string">&quot;P&quot;</span>&#125;<span class="string">,</span></span><br><span class="line">&#123;<span class="attr">item:</span> <span class="string">&quot;postcard&quot;</span>, <span class="attr">qty:</span> <span class="number">45</span>, <span class="attr">size:</span> &#123;<span class="attr">h:</span> <span class="number">10</span>, <span class="attr">w:</span> <span class="number">15.25</span>, <span class="attr">uom:</span> <span class="string">&quot;cm&quot;</span>&#125;, <span class="attr">status:</span> <span class="string">&quot;A&quot;</span>&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment"># 更新后文档</span></span><br><span class="line">&#123;<span class="attr">item:</span> <span class="string">&quot;journal&quot;</span>,  <span class="attr">qty:</span> <span class="number">25</span>, <span class="attr">size:</span> &#123;<span class="attr">h:</span> <span class="number">14</span>, <span class="attr">w:</span> <span class="number">21</span>,    <span class="attr">uom:</span> <span class="string">&quot;in&quot;</span>&#125;, <span class="attr">status:</span> <span class="string">&quot;P&quot;</span>, <span class="attr">lastModified:</span> <span class="string">ISODate(&quot;2021-07-21T02:56:56.020Z&quot;)</span>&#125;<span class="string">,</span></span><br><span class="line">&#123;<span class="attr">item:</span> <span class="string">&quot;mousepad&quot;</span>, <span class="attr">qty:</span> <span class="number">25</span>, <span class="attr">size:</span> &#123;<span class="attr">h:</span> <span class="number">19</span>, <span class="attr">w:</span> <span class="number">22.85</span>, <span class="attr">uom:</span> <span class="string">&quot;in&quot;</span>&#125;, <span class="attr">status:</span> <span class="string">&quot;P&quot;</span>, <span class="attr">lastModified:</span> <span class="string">ISODate(&quot;2021-07-21T02:56:56.020Z&quot;)</span>&#125;<span class="string">,</span></span><br><span class="line">&#123;<span class="attr">item:</span> <span class="string">&quot;postcard&quot;</span>, <span class="attr">qty:</span> <span class="number">45</span>, <span class="attr">size:</span> &#123;<span class="attr">h:</span> <span class="number">10</span>, <span class="attr">W:</span> <span class="number">15.25</span>, <span class="attr">uom:</span> <span class="string">&quot;in&quot;</span>&#125;, <span class="attr">status:</span> <span class="string">&quot;P&quot;</span>, <span class="attr">lastModified:</span> <span class="string">ISODate(&quot;2021-07-21T02:56:56.020Z&quot;)</span>&#125;</span><br></pre></td></tr></table></figure>
<p>更新操作:</p>
<ul>
<li>更新满足<code>qty &lt; 50</code>的所有文档（例1中<code>qty = 100</code>）；</li>
<li>使用<code>$set</code>修改<code>&quot;size.uom&quot; = &quot;in&quot;</code>和<code>status = &quot;p&quot;</code>；</li>
<li>使用<code>$currentDate</code>将<code>lastModified</code>更新为当前日期，不存在的字段将被创建。</li>
</ul>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">db.inventory.updateMany(</span></span><br><span class="line">    &#123;<span class="attr">&quot;qty&quot;:</span> &#123;<span class="string">$lt:</span> <span class="number">50</span>&#125;&#125;<span class="string">,</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="string">$set:</span> &#123;<span class="attr">&quot;size.uom&quot;:</span> <span class="string">&quot;in&quot;</span>, <span class="attr">status:</span> <span class="string">&quot;P&quot;</span>&#125;,</span><br><span class="line">        <span class="string">$currentDate:</span> &#123;<span class="attr">LastModified:</span> <span class="literal">true</span>&#125;</span><br><span class="line">    &#125;</span><br><span class="line"><span class="string">)</span></span><br></pre></td></tr></table></figure>
<h3 id="例3-替换单个文档"><a href="#例3-替换单个文档" class="headerlink" title="例3:替换单个文档"></a>例3:替换单个文档</h3><p>例如文档的更新情况：</p>
<ul>
<li>原始示例文档：<code>&#123;item: &quot;paper&quot;, qty: 100, size: &#123;h: 8.5, w: 11, uom: &quot;in&quot;&#125;, status: &quot;D&quot;&#125;</code>；</li>
<li>例1修改后文档：<code>&#123;item: &quot;paper&quot;, qty: 100, size: &#123;h: 8.5, w: 11, uom: &quot;cm&quot;&#125;, status: &quot;P&quot;, lastModified: ISODate(&quot;2021-07-21T02:40:43.515Z&quot;)&#125;</code>；</li>
<li>例3修改后文档：<code>&#123;item: &quot;paper&quot;, instock: [&#123;warehouse: &quot;A&quot;, qty: 60&#125;, &#123;warehouse: &quot;B&quot;, qty: 40&#125;]&#125;</code>。</li>
</ul>
<p>更新操作，直接修改整个<code>item</code>字段为<code>paper</code>的文档：<br><figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">db.inventory.replaceOne(</span></span><br><span class="line">    &#123;<span class="attr">item:</span> <span class="string">&quot;paper&quot;</span>&#125;<span class="string">,</span></span><br><span class="line">    &#123;<span class="attr">item:</span> <span class="string">&quot;paper&quot;</span>, <span class="attr">instock:</span> [&#123;<span class="attr">warehouse:</span> <span class="string">&quot;A&quot;</span>, <span class="attr">qty:</span> <span class="number">60</span>&#125;, &#123;<span class="attr">warehouse:</span> <span class="string">&quot;B&quot;</span>, <span class="attr">qty:</span> <span class="number">40</span>&#125;]&#125;</span><br><span class="line"><span class="string">)</span></span><br></pre></td></tr></table></figure></p>
<h3 id="使用聚合管道更新"><a href="#使用聚合管道更新" class="headerlink" title="使用聚合管道更新"></a>使用聚合管道更新</h3><p>从MongoDB 4.2开始，更新操作可以使用<strong>聚合管道（Aggregation Pipeline）</strong>，聚合管道可以由以下stage组成：<code>$addFields</code>、<code>$set</code>、<code>$project</code>、<code>$unset</code>、<code>$replaceRoot</code>和<code>$repaceWith</code>。</p>
<p>使用聚合管道允许更具表现力的<code>update</code>语句，例如基于当前字段值来表示条件更新，或者使用另一个字段的值更新一个字段。</p>
<ul>
<li><strong>示例1。</strong><code>db.students.updateOne(&#123;_id: 3&#125;, [&#123;$set: &#123;&quot;test3&quot;: 98，modified: &quot;$$NOW&quot;&#125;&#125;])</code>更新文档<code>_id: 3</code>，其中<code>$set</code>stage将创建不存在的字段<code>test3 = 98</code>，并将字段<code>modified</code>更新为当前时间。该操作使用「<strong>聚合变量（aggregation variable）</strong>」<code>NOW</code>获取当前时间，使用<strong>「双dollar符前缀」并「加引号」</strong>来访问变量：<code>&quot;$$NOW&quot;</code>。</li>
<li><strong>示例2。</strong>使用聚合管道来标准化文档中的字段，即集合中的文档应具有相同的字段，同时更新<code>modified</code>字段。其中：<ul>
<li>带有<code>$mergeObjects</code>表达式的<code>$replaceRoot</code>stage用来为<code>quiz1</code>、<code>quiz2</code>、<code>test1</code>和<code>test2</code>字段设置默认值，聚合变量<code>ROOT</code>指的是当前正在修改的文档。当前文档字段将覆盖默认值。</li>
<li><code>$set</code>stage将<code>modified</code>字段更新为当前时间。<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">db.students2.insertMany([</span></span><br><span class="line">    &#123;<span class="attr">&quot;_id&quot;:</span> <span class="number">1</span>, <span class="attr">quiz1:</span> <span class="number">8</span>, <span class="attr">test2:</span> <span class="number">100</span>, <span class="attr">quiz2:</span> <span class="number">9</span>, <span class="attr">modified:</span> <span class="string">new</span> <span class="string">Date(&quot;01/05/2020&quot;)</span>&#125;<span class="string">,</span></span><br><span class="line">    &#123;<span class="attr">&quot;_id&quot;:</span> <span class="number">2</span>, <span class="attr">quiz2:</span> <span class="number">5</span>, <span class="attr">test1:</span> <span class="number">80</span>, <span class="attr">test2:</span> <span class="number">89</span>, <span class="attr">modified:</span> <span class="string">new</span> <span class="string">Date(&quot;01/05/2020&quot;)</span>&#125;<span class="string">,</span></span><br><span class="line"><span class="string">])</span></span><br><span class="line"></span><br><span class="line"><span class="string">db.students2.updateMany(&#123;&#125;,</span></span><br><span class="line">    [</span><br><span class="line">        &#123;<span class="string">$replaceRoot:</span> &#123;<span class="attr">newRoot:</span></span><br><span class="line">            &#123;<span class="string">$mergeObjects:</span> [&#123;<span class="attr">quiz1:</span> <span class="number">0</span>, <span class="attr">quiz2:</span> <span class="number">0</span>, <span class="attr">test1:</span> <span class="number">0</span>, <span class="attr">test2:</span> <span class="number">0</span>&#125;, <span class="string">&quot;$$ROOT&quot;</span>]&#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;,</span><br><span class="line">        &#123;<span class="string">$set:</span> &#123;<span class="attr">modified:</span> <span class="string">&quot;$$NOW&quot;</span>&#125;&#125;</span><br><span class="line">    ]</span><br><span class="line"><span class="string">)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 结果：</span></span><br><span class="line"><span class="comment"># &#123;_id: 1, quiz1: 8, quiz2: 9, test1: 0, test2: 100, modified: ISODate(&quot;2021-07-21T04:03:43.185Z&quot;)&#125;,</span></span><br><span class="line"><span class="comment"># &#123;_id: 2, quiz1: 0, quiz2: 5, test1: 80, test2: 89, modified: ISODate(&quot;2021-07-21T04:03:43.185Z&quot;)&#125;</span></span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li><strong>示例3。</strong>使用聚合管道来计算「平均分数和成绩等级」，同时更新<code>modified</code>字段。其中：<ul>
<li>第一个<code>$set</code>stage用来①计算<code>tests</code>数组的平均值（<code>&#123;$avg: &quot;$tests&quot;&#125;</code>）并截断取整（<code>&#123;$trunc: [&lt;number&gt;, 0]&#125;</code>），将取整的值赋给<code>average</code>并创建；②将<code>modified</code>字段更新为当前时间。【<a target="_blank" rel="noopener" href="https://docs.mongodb.com/manual/reference/operator/aggregation/trunc/">$trunc用法</a>】</li>
<li>第二个<code>$set</code>stage根据上一步的<code>average</code>，使用<code>$switch</code>表达式创建<code>grade</code>。【<a target="_blank" rel="noopener" href="https://docs.mongodb.com/manual/reference/operator/aggregation/switch/">$switch用法</a>】<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">db.students3.insert([</span></span><br><span class="line">    &#123;<span class="attr">&quot;_id&quot;:</span> <span class="number">1</span>, <span class="attr">&quot;tests&quot;:</span> [<span class="number">95</span>, <span class="number">92</span>, <span class="number">98</span>], <span class="attr">&quot;modified&quot;:</span> <span class="string">ISODate(&quot;2019-01-01T00:00:00Z&quot;)</span>&#125;<span class="string">,</span></span><br><span class="line">    &#123;<span class="attr">&quot;_id&quot;:</span> <span class="number">2</span>, <span class="attr">&quot;tests&quot;:</span> [<span class="number">94</span>, <span class="number">88</span>, <span class="number">90</span>], <span class="attr">&quot;modified&quot;:</span> <span class="string">ISODate(&quot;2019-01-01T00:00:00Z&quot;)</span>&#125;<span class="string">,</span></span><br><span class="line">    &#123;<span class="attr">&quot;_id&quot;:</span> <span class="number">3</span>, <span class="attr">&quot;tests&quot;:</span> [<span class="number">70</span>, <span class="number">75</span>, <span class="number">82</span>], <span class="attr">&quot;modified&quot;:</span> <span class="string">ISODate(&quot;2019-01-01T00:00:00Z&quot;)</span>&#125;</span><br><span class="line"><span class="string">]);</span></span><br><span class="line"></span><br><span class="line"><span class="string">db.students3.updateMany(&#123;&#125;,</span></span><br><span class="line">    [</span><br><span class="line">        &#123;<span class="string">$set:</span> &#123;<span class="attr">average:</span> &#123;<span class="string">$trunc</span> [&#123;<span class="string">$avg:</span> <span class="string">&quot;$tests&quot;</span>&#125;, <span class="number">0</span>]&#125;, <span class="attr">modified:</span> <span class="string">&quot;$$NOW&quot;</span>&#125;&#125;,</span><br><span class="line">        &#123;<span class="string">$set:</span> &#123;<span class="attr">grade:</span> &#123;<span class="string">$switch:</span> &#123;</span><br><span class="line">                            <span class="attr">branches:</span> [</span><br><span class="line">                                &#123;<span class="attr">case:</span> &#123;<span class="string">$gte:</span> [<span class="string">&quot;$average&quot;</span>, <span class="number">90</span>]&#125;, <span class="attr">then:</span> <span class="string">&quot;A&quot;</span>&#125;,</span><br><span class="line">                                &#123;<span class="attr">case:</span> &#123;<span class="string">$gte:</span> [<span class="string">&quot;$average&quot;</span>, <span class="number">80</span>]&#125;, <span class="attr">then:</span> <span class="string">&quot;B&quot;</span>&#125;,</span><br><span class="line">                                &#123;<span class="attr">case:</span> &#123;<span class="string">$gte:</span> [<span class="string">&quot;$average&quot;</span>, <span class="number">70</span>]&#125;, <span class="attr">then:</span> <span class="string">&quot;C&quot;</span>&#125;,</span><br><span class="line">                                &#123;<span class="attr">case:</span> &#123;<span class="string">$gte:</span> [<span class="string">&quot;$average&quot;</span>, <span class="number">60</span>]&#125;, <span class="attr">then:</span> <span class="string">&quot;D&quot;</span>&#125;</span><br><span class="line">                            ],</span><br><span class="line">                            <span class="attr">default:</span> <span class="string">&quot;F&quot;</span></span><br><span class="line">        &#125;&#125;&#125;&#125;</span><br><span class="line">    ]</span><br><span class="line"><span class="string">)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 结果：</span></span><br><span class="line"><span class="comment"># &#123;&quot;_id&quot;: 1, &quot;tests&quot;: [95, 92, 90], &quot;modified&quot;: ISODate(&quot;2021-07-21T06:06:50.533Z&quot;), &quot;average&quot;: 92, &quot;grade&quot;: &quot;A&quot;&#125;,</span></span><br><span class="line"><span class="comment"># &#123;&quot;_id&quot;: 2, &quot;tests&quot;: [94, 88, 90], &quot;modified&quot;: ISODate(&quot;2021-07-21T06:06:50.533Z&quot;), &quot;average&quot;: 90, &quot;grade&quot;: &quot;A&quot;&#125;,</span></span><br><span class="line"><span class="comment"># &#123;&quot;_id&quot;: 3, &quot;tests&quot;: [70, 75, 82], &quot;modified&quot;: ISODate(&quot;2021-07-21T06:06:50.533Z&quot;), &quot;average&quot;: 75, &quot;grade&quot;: &quot;C&quot;&#125;,</span></span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li><strong>示例4。</strong>使用聚合管道进行array的拼接:<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">db.students4.insertMany([</span></span><br><span class="line">    &#123;<span class="attr">&quot;_id&quot;:</span> <span class="number">1</span>, <span class="attr">&quot;quizzes&quot;:</span> [<span class="number">4</span>, <span class="number">6</span>, <span class="number">7</span>]&#125;<span class="string">,</span></span><br><span class="line">    &#123;<span class="attr">&quot;_id&quot;:</span> <span class="number">2</span>, <span class="attr">&quot;quizzes&quot;:</span> [<span class="number">5</span>]&#125;<span class="string">,</span></span><br><span class="line">    &#123;<span class="attr">&quot;_id&quot;:</span> <span class="number">3</span>, <span class="attr">&quot;quizzes&quot;:</span> [<span class="number">10</span>, <span class="number">10</span>, <span class="number">10</span>]&#125;</span><br><span class="line"><span class="string">])</span></span><br><span class="line"></span><br><span class="line"><span class="string">db.students4.updateOne(&#123;_id:</span> <span class="number">2</span><span class="string">&#125;,</span></span><br><span class="line">    [</span><br><span class="line">        &#123;<span class="string">$set:</span> &#123;<span class="attr">quizzes:</span> &#123;<span class="string">$concatArrays:</span> [<span class="string">&quot;$quizzes&quot;</span>, [<span class="number">8</span>, <span class="number">6</span>]]&#125;&#125;&#125;</span><br><span class="line">    ]</span><br><span class="line"><span class="string">)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 结果:</span></span><br><span class="line"><span class="comment"># &#123;&quot;_id&quot;: 1, &quot;quizzes&quot;: [4, 6, 7]&#125;,</span></span><br><span class="line"><span class="comment"># &#123;&quot;_id&quot;: 2, &quot;quizzes&quot;: [5, 8, 6]&#125;,</span></span><br><span class="line"><span class="comment"># &#123;&quot;_id&quot;: 3, &quot;quizzes&quot;: [10, 10, 10]&#125;</span></span><br></pre></td></tr></table></figure></li>
<li><strong>示例5。</strong>使用聚合管道将「摄氏温度」转换为「华氏温度」，其中：<ul>
<li>管道包含<code>$addFields</code>stage（与<code>$set</code>等价），用以创建新的数组字段<code>tempsF</code>（包含华氏温度的数组）；</li>
<li>该stage使用<code>$map``$add</code>和<code>$multiply</code>表达式来进行温度转换$F=C\times \frac{9}{5}+32$。【<a target="_blank" rel="noopener" href="https://docs.mongodb.com/manual/reference/operator/aggregation/map/">$map用法</a>，对<code>len(tempsC)</code>无要求】<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">db.temperatures.insertMany([</span></span><br><span class="line">    &#123;<span class="attr">&quot;_id&quot;:</span> <span class="number">1</span>, <span class="attr">&quot;date&quot;:</span> <span class="string">ISODate(&quot;2019-06-23&quot;)</span>, <span class="attr">&quot;tempsC&quot;:</span> [ <span class="number">4</span>, <span class="number">12</span>, <span class="number">17</span>]&#125;<span class="string">,</span></span><br><span class="line">    &#123;<span class="attr">&quot;_id&quot;:</span> <span class="number">2</span>, <span class="attr">&quot;date&quot;:</span> <span class="string">ISODate(&quot;2019-07-07&quot;)</span>, <span class="attr">&quot;tempsC&quot;:</span> [<span class="number">14</span>, <span class="number">24</span>, <span class="number">11</span>]&#125;<span class="string">,</span></span><br><span class="line">    &#123;<span class="attr">&quot;_id&quot;:</span> <span class="number">3</span>, <span class="attr">&quot;date&quot;:</span> <span class="string">ISODate(&quot;2019-10-30&quot;)</span>, <span class="attr">&quot;tempsC&quot;:</span> [<span class="number">18</span>,  <span class="number">6</span>,  <span class="number">8</span>]&#125;</span><br><span class="line"><span class="string">])</span></span><br><span class="line"></span><br><span class="line"><span class="string">db.temperatures.updateMany(&#123;&#125;,</span></span><br><span class="line">    [</span><br><span class="line">        &#123;<span class="string">$addFields:</span> &#123;<span class="attr">&quot;tempsF&quot;:</span> &#123;</span><br><span class="line">            <span class="string">$map:</span> &#123;</span><br><span class="line">                <span class="attr">input:</span> <span class="string">&quot;$tempsC&quot;</span>,</span><br><span class="line">                <span class="attr">as:</span> <span class="string">&quot;celsius&quot;</span>,</span><br><span class="line">                <span class="attr">in:</span> &#123;<span class="string">$add:</span> [&#123;<span class="string">$multiply:</span> [<span class="string">&quot;$$celsius&quot;</span>, <span class="number">9</span><span class="string">/5</span>]&#125;, <span class="number">32</span>]&#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;&#125;&#125;</span><br><span class="line">    ]</span><br><span class="line"><span class="string">)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 结果：</span></span><br><span class="line"><span class="comment"># &#123;&quot;_id&quot;: 1, &quot;date&quot;: ISODate(&quot;2019-06-23T00:00:00.000Z&quot;), &quot;tempsC&quot;: [ 4, 12, 17], &quot;tempsF&quot;: [39.2, 53.6, 62.6]&#125;,</span></span><br><span class="line"><span class="comment"># &#123;&quot;_id&quot;: 2, &quot;date&quot;: ISODate(&quot;2019-07-07T00:00:00.000Z&quot;), &quot;tempsC&quot;: [14, 24, 11], &quot;tempsF&quot;: [57.2, 75.2, 51.8]&#125;,</span></span><br><span class="line"><span class="comment"># &#123;&quot;_id&quot;: 3, &quot;date&quot;: ISODate(&quot;2019-10-30T00:00:00.000Z&quot;), &quot;tempsC&quot;: [18,  6,  8], &quot;tempsF&quot;: [64.4, 42.8, 46.4]&#125;</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
</ul>
<h3 id="update方法"><a href="#update方法" class="headerlink" title="update方法"></a>update方法</h3><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">db<span class="selector-class">.collection</span><span class="selector-class">.updateOne</span>()</span><br><span class="line">db<span class="selector-class">.collection</span><span class="selector-class">.updateMany</span>()</span><br><span class="line">db<span class="selector-class">.collection</span><span class="selector-class">.replaceOne</span>()</span><br><span class="line">db<span class="selector-class">.collection</span><span class="selector-class">.update</span>()</span><br><span class="line">db<span class="selector-class">.collection</span><span class="selector-class">.findOneAndReplace</span>()</span><br><span class="line">db<span class="selector-class">.collection</span><span class="selector-class">.findOneAndUpdate</span>()</span><br><span class="line">db<span class="selector-class">.collection</span><span class="selector-class">.findAndModify</span>()</span><br><span class="line">db<span class="selector-class">.collection</span><span class="selector-class">.bulkWrite</span>()</span><br></pre></td></tr></table></figure>
<h2 id="5-删除操作"><a href="#5-删除操作" class="headerlink" title="5.删除操作"></a>5.删除操作</h2><p>从集合中删除文档，具有<strong>「原子性」</strong>，也可指定条件或过滤器：<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">db<span class="selector-class">.collection</span><span class="selector-class">.deleteOne</span>(<span class="attribute">filter</span>)</span><br><span class="line">db<span class="selector-class">.collection</span><span class="selector-class">.deleteMany</span>(<span class="attribute">filter</span>)</span><br></pre></td></tr></table></figure></p>
<ul>
<li>删除所有文档。将过滤器文档置空：<code>db.inventory.deleteMany(&#123;&#125;)</code>。</li>
<li>删除所有符合条件的文档。指定用于标识要删除文档的条件或过滤器，过滤器语法与查询操作相同。在「<strong>查询过滤器文档（query filter docuent）</strong>」中使用<code>field: value</code>表达式来指定相等匹配条件：<code>&#123;&lt;field1&gt;: &lt;value1&gt;, ...&#125;</code>，同理，将<code>value</code>替换成「<strong>查询操作符</strong>」来指定匹配条件：<code>&#123;&lt;field1&gt;: &#123;&lt;operator1&gt;: &lt;value1&gt;&#125;, ...&#125;</code>。</li>
<li>只删除一个符合条件的文档。即使多个文档相匹配，也只删除第一个：<code>db.collection.deleteOne(filter)</code>。</li>
<li>删除方法：<ul>
<li><code>db.collection.deleteOne()</code>；</li>
<li><code>db.collection.deleteMany()</code>；</li>
<li><code>db.collection.remove()</code>；</li>
<li><code>db.collection.findOneAndDelete()</code>；</li>
<li><code>db.collection.findAndModify()</code>；</li>
<li><code>db.collection.bulkWrite()</code>。</li>
</ul>
</li>
</ul>

      
    </div>
    <div class="article-footer">
      <blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    <li class="post-copyright-license">
      <strong>文章作者： </strong><a href="https://hwame.top" style="color:#E541E5;"> 鴻塵</a>
    </li>
    
    <li class="post-copyright-link hidden-xs">
      <strong>本文链接：</strong>
      <a href="https://hwame.top/20210716/mongodb-crud-operations.html" title="MongoDB增删改查" target="_blank" rel="external" style="color:#E541E5;">https://hwame.top/20210716/mongodb-crud-operations.html</a>
    </li>
    
    <li class="post-copyright-license">
      <strong>版权声明： </strong> 本博客所有文章除特别声明外，均采用《<a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external" style="color:#E541E5;"><u>CC BY 4.0 CN协议</u></a>》许可协议。转载请注明出处！
    </li>
  </ul>
</blockquote>


<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://hwame.top" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://hwame.top" target="_blank"><span class="text-dark">鴻塵</span><small class="ml-1x">Pythoner, Data Analyst</small></a></h3>
        <div>个人简介：处女座不适合做码农。</div>
      </div>
    </figure>
  </div>
</div>


    </div>
  </article>
  
    
  <section id="comments">
  	
      <div id="vcomments"></div>
    
  </section>


  
</div>

  <nav class="bar bar-footer clearfix" data-stick-bottom>
  <div class="bar-inner">
  
  <ul class="pager pull-left">
    
    <li class="prev">
      <a href="/20210806/mongodb-aggregation-operation.html" title="MongoDB聚合操作"><i class="icon icon-angle-left" aria-hidden="true"></i><span>&nbsp;&nbsp;上一篇</span></a>
    </li>
    
    
    <li class="next">
      <a href="/20210629/python-virtual-environment.html" title="Python虚拟环境"><span>下一篇&nbsp;&nbsp;</span><i class="icon icon-angle-right" aria-hidden="true"></i></a>
    </li>
    
    
    <li class="toggle-toc">
      <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false" title="文章目录" role="button">
        <span style="color:#C71585">[&nbsp;</span><span style="color:#C71585">文章目录</span>
        <i class="text-collapsed icon icon-anchor"></i>
        <i class="text-in icon icon-close"></i>
        <span style="color:#C71585">]</span>
      </a>
    </li>
    
  </ul>
  
  
  
  <div class="bar-right">
    
    <div class="share-component" data-sites="weibo,qq,wechat,facebook,twitter" data-mobile-sites="weibo,wechat,qq,qzone"></div>
    
  </div>
  </div>
</nav>
  


</main>

  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
	
	
    <ul class="social-links">
    	
        <li><a href="https://github.com/hwame" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="https://weibo.com/hwamei" target="_blank" title="Weibo" data-toggle=tooltip data-placement=top><i class="icon icon-weibo"></i></a></li>
        
        <li><a href="https://www.zhihu.com/people/hwame" target="_blank" title="Zhihu" data-toggle=tooltip data-placement=top><i class="icon icon-zhihu"></i></a></li>
        
        <li><a href="https://segmentfault.com/u/hwame" target="_blank" title="Segmentfault" data-toggle=tooltip data-placement=top><i class="icon icon-segmentfault"></i></a></li>
        
        <li><a href="https://gitee.com/hwame" target="_blank" title="Gitee" data-toggle=tooltip data-placement=top><i class="icon icon-gitee"></i></a></li>
        
        <li><a href="/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    <div class="copyright">
    	
        &copy; 2025 鴻塵
        
        
        <div class="publishby" style="font-family:Courier">
            <span id="busuanzi_container_site_pv">
                <i class="icon icon-eye"></i><span id="busuanzi_value_site_pv" style="font-family:Courier"></span>&nbsp;
                <i class="icon icon-users"></i><span id="busuanzi_value_site_uv" style="font-family:Courier"></span>
            </span>
            <!--
            <br>✯<a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/" style="color:#0FFFAA">鄂ICP备2020019329号</a>
            -->
            <br><i class="icon icon-clock" style="transform:rotate(90deg)"></i><span id="sitetime" style="font-family:Courier"></span>
        </div>
        
        <!--
        <div class="publishby">
        	Theme by <a href="https://github.com/cofess" target="_blank"> cofess </a>base on <a href="https://github.com/cofess/hexo-theme-pure" target="_blank">pure</a>.
        </div>
        -->
    </div>
    
</footer>
<script>
    function siteTime(){
        window.setTimeout("siteTime()", 1000);
        var seconds = 1000;
        var minutes = seconds * 60;
        var hours = minutes * 60;
        var days = hours * 24;
        var years = days * 365;
        var today = new Date();
        var todayYear = today.getFullYear();
        var todayMonth = today.getMonth()+1;
        var todayDate = today.getDate();
        var todayHour = today.getHours();
        var todayMinute = today.getMinutes();
        var todaySecond = today.getSeconds();
        /* Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
        year - 作为date对象的年份，为4位年份值
        month - 0-11之间的整数，做为date对象的月份
        day - 1-31之间的整数，做为date对象的天数
        hours - 0(午夜24点)-23之间的整数，做为date对象的小时数
        minutes - 0-59之间的整数，做为date对象的分钟数
        seconds - 0-59之间的整数，做为date对象的秒数
        microseconds - 0-999之间的整数，做为date对象的毫秒数 */
        var t1 = Date.UTC(2020,05,19,21,20,52); //建站时间
        var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
        var diff = t2-t1;
        var diffYears = Math.floor(diff/years);
        var diffDays = Math.floor((diff/days)-diffYears*365);
        var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
        var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
        var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
        // 将「数字」转「补零字符串」
        var y = diffYears.toString()
        var d = diffDays.toString().padStart(3, '0')
        var h = diffHours.toString().padStart(2, '0')
        var m = diffMinutes.toString().padStart(2, '0')
        var s = diffSeconds.toString().padStart(2, '0')
        document.getElementById("sitetime").innerHTML=y+":"+d+":"+h+":"+m+":"+s;
    }
    siteTime();
</script>
  <script src="//cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
<div id="go-top"></div>
<style type="text/css">
#go-top {
 width:40px;height:40px;
 background-color:#DDA0DD;
 position:relative;
 border-radius:20px;
 position:fixed;right:20px;bottom:50px;
 cursor:pointer;display:none;
}
#go-top:after {
 content:" ";
 position:absolute;left:14px;top:14px;
 border-top:2px solid #fff;border-right:2px solid #fff;
 width:12px;height:12px;
 transform:rotate(-45deg);
}
#go-top:hover {
 background-color:#8A2BE2;
}
</style>
<script>
$(function () {
  var top=$("#go-top");
  $(window).scroll(function () {
    ($(window).scrollTop() > 300) ? top.show(300) : top.hide(200);
    $("#go-top").click(function () {
      $('body,html').animate({scrollTop:0});
      return false();
    })
  });
});
</script>

<script src="/js/plugin.min.js"></script>


<script src="/js/application.js"></script>


    <script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>

<script src="/js/insight.js"></script>





   




   
    

  <script src='/waline.js'></script>
  <link rel="stylesheet" type="text/css" href="/waline.css" />
  
  <script type="text/javascript">
 
  
Waline.init({
      el: '#vcomments',
      serverURL: 'https://waline.hwame.top',
});
  </script>

     


<!-- 20201211添加判断 -->

   
  <script src="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script>
  <script>
  //利用 FancyBox 实现点击图片放大
  $(document).ready(function() {
    $('article img').not('[hidden]').not('.panel-body img').each(function() {
      var $image = $(this);
      var imageCaption = $image.attr('alt');
      var $imageWrapLink = $image.parent('a');
      if ($imageWrapLink.length < 1) {
        var src = this.getAttribute('src');
        var idx = src.lastIndexOf('?');
        if (idx != -1) {
          src = src.substring(0, idx);
        }
        $imageWrapLink = $image.wrap('<a href="' + src + '"></a>').parent('a');
      }
      $imageWrapLink.attr('data-fancybox', 'images');
      if (imageCaption) {
        $imageWrapLink.attr('data-caption', imageCaption);
      }
    });
    $().fancybox({
      selector: '[data-fancybox="images"]',
      hash: false,
      loop: true,
    });
  });
  </script>







  
  <style>
    .copy-btn {
      display: inline-block;
      padding: 6px 12px;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
      color: #333;
      white-space: nowrap;
      vertical-align: middle;
      cursor: pointer;
      background-color: #eee;
      background-image: linear-gradient(#fcfcfc, #eee);
      border: 1px solid #d5d5d5;
      border-radius: 3px;
      user-select: none;
      outline: 0;
    }

    .highlight-wrap .copy-btn {
      transition: opacity .3s ease-in-out;
      opacity: 0;
      padding: 2px 6px;
      position: absolute;
      right: 4px;
      top: 8px;
      z-index: 2;
    }

    .highlight-wrap:hover .copy-btn,
        .highlight-wrap .copy-btn:focus {
      opacity: 1
    }

    .highlight-wrap {
      position: relative;
    }
  </style>
  
  <script>
    addLoadEvent(()=>{
      $('.highlight').each(function (i, e) {
        var $wrap = $('<div>').addClass('highlight-wrap')
        $(e).after($wrap)
        $wrap.append($('<button>').addClass('copy-btn').append('一键复制').on('click', function (e) {
          var code = $(this).parent().find(".code")[0].innerText
          
          var ta = document.createElement('textarea')
          document.body.appendChild(ta)
          ta.style.position = 'absolute'
          ta.style.top = '0px'
          ta.style.left = '0px'
          ta.value = code
          ta.select()
          ta.focus()
          var result = document.execCommand('copy')
          document.body.removeChild(ta)
          
            if(result)$(this).text('复制成功')
            else $(this).text('复制失败')
          
          $(this).blur()
        })).on('mouseleave', function (e) {
          var $b = $(this).find('.copy-btn')
          setTimeout(function () {
            $b.text('一键复制')
          }, 300)
        }).append(e)
      })
    })
  </script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [ ["$","$"], ["\\(","\\)"] ],
            skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
            processEscapes: true
        }
    });
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax();
        for (var i = 0; i < all.length; ++i)
            all[i].SourceElement().parentNode.className += ' has-jax';
    });
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</body>
</html>